<?php

namespace App\Services;

use App\Models\OrderInfo;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class OrderService
{
    public function paySuccess($order_nu)
    {
        try {
            $orderInfo = OrderInfo::where('order_nu', $order_nu)->first();
            if (empty($orderInfo)) {
                throw new \Exception('订单号错误');
            }
            if ($orderInfo->status != 0) {
                throw new \Exception('订单状态不符');
            }

            // 确认支付
            $paymentResult = (new PaymentService())->confirmPayment($order_nu);
            if ($paymentResult['code'] !== 0) {
                throw new \Exception($paymentResult['msg']);
            }

            // 支付成功充值动态套餐流量
            if ($orderInfo->proxy_type == 1) {
                $proxyService = new ProxyService();
                $result = $proxyService->rechargeTraffic($orderInfo->user_id, $orderInfo->order_nu, $orderInfo->quantity);
                if ($result['code'] !== 0) {
                    throw new \Exception('充值流量失败：' . $result['msg']);
                }
            } else {
                $proxyService = new ProxyService();
                $result = $proxyService->createStaticOrder($orderInfo->user_id, $orderInfo->order_nu);
                if ($result['code'] !== 0) {
                    throw new \Exception('静态购买失败：' . $result['msg']);
                }
            }

            // 更新订单状态
            $orderInfo->status = 1;
            $orderInfo->is_verify = 1;
            $orderInfo->save();

            // 增加累计消费额
            User::where('id', $orderInfo->user_id)->increment('amount', $orderInfo->amount);

            return [
                'code' => 0,
                'msg' => '操作成功'
            ];

        } catch (\Exception $e) {
            Log::info('发放权益异常 ' . $e->getMessage());
            return [
                'code' => -1,
                'msg' => $e->getMessage()
            ];
        }
    }
}
